package com.assembly.videolist.ui

import android.annotation.SuppressLint
import android.graphics.SurfaceTexture
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.aliyun.player.AliListPlayer
import com.aliyun.player.AliPlayerFactory
import com.aliyun.player.IPlayer
import com.aliyun.player.nativeclass.PlayerConfig
import com.assembly.videolist.R
import com.assembly.videolist.adapter.OnViewPagerAliyunListener
import com.assembly.videolist.adapter.PagerLayoutManager
import com.assembly.videolist.base.VideoListBean
import kotlinx.android.synthetic.main.video_list_layout.*

/**
 * descrition:短视频列表
 */
class VideoListActivity: AppCompatActivity()  {
    private lateinit var mViewPagerLayoutManager: PagerLayoutManager
    var videoUrlList:MutableList<VideoListBean> = mutableListOf()
    /**
     * 播放器
     */
    var aliyunListPlayer: AliListPlayer? = null
    /**
     * 是否暂停
     */
    private var mIsPause = false
    private lateinit var listPlayerTextureview: TextureView
    /**
     * 播放/暂停imageview
     */
    var mPlayIconImageView: ImageView? = null
    var isLoad: Boolean = false
    /**
     * 当前滑动标记
     */
    private var mCurrentPosition = 0
    private var mListPlayerContainer: View? = null
    private lateinit var mAdapter: MyRecyclerViewAdapter
    /**
     * 分页大小
     */
    var pageSize = 5
    /**
     * 当前分页
     */
    var page = 1
    /**
     * 手势监听器
     */
    private var mGestureDetector: GestureDetector? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.video_list_layout)
        initPlayer()
        initListPlayerView()
        initData()
        addUrl()
    }

    /**
     * 初始化播放器
     */
    private fun initPlayer() {
        aliyunListPlayer = AliPlayerFactory.createAliListPlayer(this)
        //设置预加载个数。总共加载的个数为： 1 + count*2。
        aliyunListPlayer!!.setPreloadCount(2)
        aliyunListPlayer!!.isLoop = true
        aliyunListPlayer!!.scaleMode = IPlayer.ScaleMode.SCALE_ASPECT_FILL
        val config: PlayerConfig = aliyunListPlayer!!.config
        config.mClearFrameWhenStop = true
        aliyunListPlayer!!.config = config
    }

    /**
     * 初始化播放界面
     */
    @SuppressLint("ClickableViewAccessibility")
    private fun initListPlayerView() {
        mListPlayerContainer = View.inflate(this, R.layout.layout_list_player_view, null)
        mPlayIconImageView = mListPlayerContainer!!.findViewById(R.id.iv_play_icon)
//        mPlayIconImageView.visibility = View.GONE
        listPlayerTextureview = mListPlayerContainer!!.findViewById(R.id.list_player_textureview)

        //TextureView
        listPlayerTextureview.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, width: Int, height: Int) {
                val mSurface = Surface(surfaceTexture)
                if (aliyunListPlayer != null) {
                    aliyunListPlayer!!.setSurface(mSurface)
                    aliyunListPlayer!!.redraw()
                }
            }

            override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
                if (aliyunListPlayer != null) {
                    aliyunListPlayer!!.redraw()
                }
            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                return true
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
        }

        //手势监听器
        mGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
            override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
//                onPauseClick()
                if (mIsPause) {
                    mPlayIconImageView!!.visibility = View.GONE

                    resumePlay()
                } else {
                    mPlayIconImageView!!.visibility = View.VISIBLE
                    pausePlay()
                }
                return true
            }

            override fun onDown(e: MotionEvent): Boolean {
                return true
            }
        })
//        //播放列表界面的touch事件由手势监听器处理
        mListPlayerContainer!!.setOnTouchListener { _, motionEvent ->
            mGestureDetector!!.onTouchEvent(motionEvent)
        }
    }

    /**
     * 初始化列表
     */
    private fun initData(){
        mViewPagerLayoutManager = PagerLayoutManager(this)
        mViewPagerLayoutManager.isItemPrefetchEnabled = true

        video_listview.layoutManager = mViewPagerLayoutManager
        video_listview.setHasFixedSize(true)

        if (mViewPagerLayoutManager.viewPagerListenerIsNull()) {
            mViewPagerLayoutManager.setOnViewPagerListener(object : OnViewPagerAliyunListener {
                override fun onInitComplete() {
//                val itemCount: Int = mRecyclerViewAdapter.getItemCount()
//                if (itemCount - position < com.aliyun.player.aliyunlistplayer.view.AliyunListPlayerView.DEFAULT_PRELOAD_NUMBER && !mIsLoadingData && !isEnd) {
//                    // 正在加载中, 防止网络太慢或其他情况造成重复请求列表
//                    mIsLoadingData = true
//                    loadMore() 
//                } osition) 
                    autoPlayVideo(0)
                }

                override fun onPageRelease(isNext: Boolean, position: Int, view: View?) {
                    isLoad = isNext
                    if (mCurrentPosition == position) {
                        stopPlay()
//                        val holder: MyRecyclerViewAdapter.MyViewHolder = kankan_listview.findViewHolderForLayoutPosition(position) as MyRecyclerViewAdapter.MyViewHolder
//                        holder.coverImage.visibility = View.VISIBLE
                    }
                }

                override fun onPageSelected(position: Int, bottom: Boolean, view: View?) {
                    //重新选中视频不播放，如果该位置被stop过则会重新播放视频
                    if (mCurrentPosition == position) {
                        return
                    }
                    //如果滑动到最后一个缓存的视频 开始加载更多
                    if (position == videoUrlList.size - 1) {
                        if (isLoad) {
                            page++
                            addUrl()
                        }
                    }
                    mCurrentPosition = position
                    //开始播放选中视频
                    autoPlayVideo(position)
                }
            })
        }


        /**
         * 准备成功事件
         */
        aliyunListPlayer!!.setOnPreparedListener {
            if (!mIsPause) {
                aliyunListPlayer!!.start()
            }
        }

        /**
         * 首帧渲染显示事件
         */
        aliyunListPlayer!!.setOnRenderingStartListener {
            if (video_listview != null) {
                val mViewHolder: MyRecyclerViewAdapter.MyViewHolder =
                    video_listview.findViewHolderForLayoutPosition(mCurrentPosition) as MyRecyclerViewAdapter.MyViewHolder
                mViewHolder.coverImage.visibility = View.GONE
            }
        }

        /**
         * 失败回调
         */
        aliyunListPlayer!!.setOnErrorListener { errorInfo ->
            run {
                Log.e("error", errorInfo.code.toString() + " --- " + errorInfo.msg)
            }
        }

    }

    /**
     * 加载数据
     *
     */
    fun addUrl(){
        videoUrlList.add(VideoListBean(urls = "https://index.jwell56.com/opt/image/media/20220606/20220606133705_219.mp4"))
        videoUrlList.add(VideoListBean(urls = "http://10.0.60.69:8080/opt/image/media/20220608/20220608163106_939.mp4"))
        videoUrlList.add(VideoListBean(urls = "http://10.0.60.69:8080/opt/image/media/20220608/20220608170058_652.mp4"))
        videoUrlList.add(VideoListBean(urls = "http://10.0.60.69:8080/opt/image/media/20220608/20220608161153_408.mp4"))
        videoUrlList.add(VideoListBean(urls = "http://10.0.60.69:8080/opt/image/media/20220608/20220608163106_939.mp4"))

        if(page == 1){
            mAdapter = MyRecyclerViewAdapter()
            video_listview.adapter = mAdapter
        }

        isLoad = videoUrlList.size >= pageSize
        for (i in 0 until videoUrlList.size) {
            //添加URL源
            aliyunListPlayer!!.addUrl(videoUrlList[i].url, i.toString())
        }
    }


    /**
     * 播放视频
     */
     fun autoPlayVideo(postion: Int) {
        if (postion < 0 || postion > videoUrlList.size) {
            return
        }
        try {
            mViewPagerLayoutManager.findViewByPosition(postion)

            //恢复界面状态
            mIsPause = false
            mPlayIconImageView!!.visibility = View.GONE

            val mViewHolder: MyRecyclerViewAdapter.MyViewHolder = video_listview.findViewHolderForLayoutPosition(postion) as MyRecyclerViewAdapter.MyViewHolder
            val parent = mListPlayerContainer!!.parent

            if (parent is FrameLayout) {
                (parent as ViewGroup).removeView(mListPlayerContainer)
            }
            mViewHolder.contentLayout.addView(mListPlayerContainer, 0)
            aliyunListPlayer!!.moveTo(postion.toString())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 停止视频播放
     */
    private fun stopPlay() {
        try {
            val parent: ViewParent = mListPlayerContainer!!.parent
            if (parent is FrameLayout) {
                parent.removeView(mListPlayerContainer)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        aliyunListPlayer!!.stop()
        aliyunListPlayer!!.setSurface(null)
    }

    /**
     * 暂停播放
     */
     fun pausePlay() {
        mIsPause = true
        if (aliyunListPlayer != null) {
            if (mPlayIconImageView != null) {
                mPlayIconImageView!!.visibility = View.VISIBLE
            }

            aliyunListPlayer!!.pause()
        }
    }

    /**
     * 恢复播放
     */
     fun resumePlay() {
        mIsPause = false
        if (aliyunListPlayer != null ) {
            if (mPlayIconImageView != null) {
                mPlayIconImageView!!.visibility = View.GONE
            }
            aliyunListPlayer!!.start()
        }
    }

    /**
     * adapter
     */
    inner class MyRecyclerViewAdapter: RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            return MyViewHolder(
                LayoutInflater.from(
                this@VideoListActivity).inflate(R.layout.video_list_item_layout, parent,
                false))
        }

        @SuppressLint("LongLogTag")
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        }

        override fun getItemCount(): Int {
            return videoUrlList.size
        }

        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
              val contentLayout: FrameLayout = itemView.findViewById(R.id.content_layout)
            var coverImage: ImageView = itemView.findViewById(R.id.cover_image)


        }
    }

    /**
     * 销毁
     */
    private fun destroy() {
        if (aliyunListPlayer != null) {
            aliyunListPlayer!!.stop()
            aliyunListPlayer!!.release()
        }
    }

    override fun onPause() {
        super.onPause()
        pausePlay()
    }

    override fun onResume() {
        super.onResume()
        resumePlay()
    }

    override fun onDestroy() {
        super.onDestroy()
        destroy()
    }

}